package com.action.mvc.auth.controller;

import com.action.mvc.auth.common.AjaxResult;
import com.action.mvc.auth.entity.Role;
import com.action.mvc.auth.entity.RoleFunction;
import com.action.mvc.auth.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Wuxiang on 2017/4/24.
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @RequestMapping("/index")
    public String index() {
        return "role_list";
    }

    @RequestMapping("/getRoles")
    @ResponseBody
    public List<Role> getRoles(Integer page, Integer size){
        return roleService.getRoles(page, size);
    }

    @RequestMapping(value = "/addEditRole",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addEditRole(Role role){
        String functionIds = role.getFunctionIds();
        //得到角色的functionid
        String[] idArray = functionIds.split(",");
        List<RoleFunction> rfs = new ArrayList<>();
        for (int i = 0; i < idArray.length; i++) {
            RoleFunction rf = new RoleFunction();
            rf.setFunctionId(Long.valueOf(idArray[i]));
            rf.setStatus(1);
            rfs.add(rf);
        }
        if(null == role.getId()){
            roleService.addRole(role, rfs);
        }else{
            roleService.editRole(role, rfs);
        }

        return AjaxResult.success();
    }

    @RequestMapping("/deleteRole")
    @ResponseBody
    public AjaxResult deleteRole(Long id){
        roleService.deleteRole(id);
        return AjaxResult.success();
    }
}
